import { Component, Inject, Input, OnChanges, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import {DatePipe} from '@angular/common';
import {HomeService} from '@app/services/home.service';
@Component({
  selector: 'app-home-request',
  templateUrl: './request.component.html',
  styleUrls: ['./request.component.less'],
  providers: [DatePipe],
})
export class RequestComponent implements OnInit, OnChanges {
  constructor(
    @Inject(NzMessageService) private nzMessageService,
    private datePipe: DatePipe,
    private homeService: HomeService
  ) {}
  method = 'GET';
  url = '';
  request = {Params: '', Headers: '', Body: ''};
  response = '';
  resultLoading = false;
  tabs = ['Params', 'Headers', 'Body'];

  @Input() history;
  ngOnInit(): void {}

  ngOnChanges(changeRecord): void {
    console.log(changeRecord);
    console.log(this.history);
    if (this.history && this.history.method) {
      this.method = this.history.method || 'GET';
      this.url = this.history.url || '';
      this.request.Params = this.history.params || '';
      this.request.Headers = this.history.headers || '';
      this.request.Body = this.history.body || '';
    }
  }

  send(): void {
    console.log(this.method, this.url, this.request);
    if (!this.url) {
      this.nzMessageService.error('请输入URL', {nzDuration: 1000});
      return;
    }
    if (this.url.indexOf('http://') < 0 && this.url.indexOf('https://') < 0) {
      this.nzMessageService.error('URL地址以http或者https开头', {
        nzDuration: 1000,
      });
      return;
    }
    // const params = {};
    // this.request.Params.split('\n').map((e) => {
    //   const kv = e.split(':');
    //   params[kv[0]] = kv[1];
    // });
    // const headers = {};
    // this.request.Headers.split('\n').map((e) => {
    //   const kv = e.split(':');
    //   headers[kv[0]] = kv[1];
    // });

    this.resultLoading = true;
    this.homeService
      .history_add_item({
        id: 0,
        method: this.method,
        url: this.url,
        params: this.request.Params,
        body: this.request.Body,
        headers: this.request.Headers,
      })
      .subscribe(
        (resp) => {
          console.log(resp, 11111111111);
          this.response = resp.data;
          this.resultLoading = false;
        },
        (error) => {
          console.log(error);
          this.resultLoading = false;
        }
      );
  }
}
